/*
 * www.acooly.cn Inc.
 * Copyright (c) 2018 All Rights Reserved
 */

/*
 * 修订记录:
 * zhangpu@acooly.cn 2018-01-24 17:39 创建
 */
package com.acooly.module.openapi.client.provider.yipay.service;

import com.acooly.core.utils.security.RSA;
import com.acooly.module.openapi.client.provider.yipay.OpenAPIClientYipayProperties;
import com.acooly.module.openapi.client.provider.yipay.YipayConstants;
import com.acooly.module.safety.key.AbstractKeyLoadManager;
import com.acooly.module.safety.key.KeyStoreLoader;
import com.acooly.module.safety.support.CodecEnum;
import com.acooly.module.safety.support.KeyStoreInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author zhangpu 2018-01-24 17:39
 */
@Component
public class YipayKeyLoader extends AbstractKeyLoadManager<KeyStoreInfo> implements KeyStoreLoader {

    @Autowired
    protected OpenAPIClientYipayProperties openAPIClientYipayProperties;

    @Override
    public KeyStoreInfo doLoad(String principal) {
        KeyStoreInfo keyStoreInfo = new KeyStoreInfo();
        keyStoreInfo.setKeyStoreUri(openAPIClientYipayProperties.getKeystore());
        keyStoreInfo.setKeyStorePassword(openAPIClientYipayProperties.getKeystorePswd());
        keyStoreInfo.setCertificateUri(openAPIClientYipayProperties.getGatewayCert());
        keyStoreInfo.setKeyStoreType(KeyStoreInfo.KEY_STORE_PKCS12);
        //待签明文字符集
        keyStoreInfo.setPlainEncode("UTF-8");
        // 签名的算法
        keyStoreInfo.setSignatureAlgo(RSA.SIGN_ALGO_SHA2);
        // 签名结果怎么编码
        keyStoreInfo.setSignatureCodec(CodecEnum.BASE64);
        // 最后load下，内部会缓存。
        keyStoreInfo.loadKeys();
        return keyStoreInfo;
    }

    @Override
    public String getProvider() {
        return YipayConstants.PROVIDER_NAME;
    }
}
